import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../services/token_manager.dart';
import '../services/constants.dart';
import 'goodsDetail.dart';
import '../services/market_events.dart';

class MyProductScreen extends StatefulWidget {
  @override
  State<MyProductScreen> createState() => _MyProductScreenState();
}

class _MyProductScreenState extends State<MyProductScreen> {
  List<Map<String, dynamic>> goodsList = [];
  String userEmail = '';
  bool loading = true;

  @override
  void initState() {
    super.initState();
    _initAndLoad();
  }

  Future<void> _initAndLoad() async {
    final info = await TokenManager.instance.getUserInfo();
    userEmail = info['email'] ?? '';
    await _loadGoods();
  }

  Map<String, String> _headers() {
    return {
      'Content-Type': 'application/json',
      if (userEmail.isNotEmpty) 'email': userEmail,
    };
  }

  Future<void> _loadGoods() async {
    setState(() { loading = true; });
    try {
      final url = Uri.parse('${Constants.serverUrl}goods/getMyGoodsList');
      final res = await http.get(url, headers: _headers());
      if (res.statusCode == 200) {
        final data = jsonDecode(res.body);
        if (data['code'] == 0 && data['data'] is List) {
          goodsList = List<Map<String, dynamic>>.from(data['data']);
        }
      }
    } catch (_) {}
    setState(() { loading = false; });
  }

  Future<void> _deleteGoods(int id) async {
    try {
      final url = Uri.parse('${Constants.serverUrl}goods/delete');
      final res = await http.post(url, headers: _headers(), body: jsonEncode({'id': id}));
      if (res.statusCode == 200) {
        await _loadGoods();
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已删除')));
        }
        // 通知市场页刷新
        MarketEvents.instance.notifyChanged();
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('删除失败 (${res.statusCode})')));
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('删除失败: $e')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('我的商品')),
      body: loading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _loadGoods,
              child: goodsList.isEmpty
                  ? ListView(children: const [SizedBox(height: 200), Center(child: Text('暂无商品'))])
                  : ListView.separated(
                      padding: const EdgeInsets.all(10),
                      itemCount: goodsList.length,
                      separatorBuilder: (context, index) => const SizedBox(height: 10),
                      itemBuilder: (context, index) {
                        final item = goodsList[index];
                        final List<String> images = (item['images'] is String)
                            ? (item['images'] as String)
                                .split(',')
                                .where((e) => e.trim().isNotEmpty)
                                .toList()
                            : <String>[];
                        return InkWell(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (_) => GoodsDetailPage(goods: item),
                              ),
                            );
                          },
                          child: Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Row(
                              children: [
                                Container(
                                  width: 80,
                                  height: 80,
                                  color: Colors.grey[200],
                                  child: images.isNotEmpty
                                      ? Image.network(images.first, fit: BoxFit.cover)
                                      : Icon(Icons.image_outlined, color: Colors.grey[400]),
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        (item['name'] ?? '').toString(),
                                        style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      const SizedBox(height: 8),
                                      Text(
                                        '¥' + (item['price'] ?? '').toString(),
                                        style: TextStyle(color: Colors.red[700], fontSize: 16, fontWeight: FontWeight.bold),
                                      ),
                                    ],
                                  ),
                                ),
                                const SizedBox(width: 12),
                                OutlinedButton(
                                  onPressed: () async {
                                    final confirm = await showDialog<bool>(
                                      context: context,
                                      builder: (context) => AlertDialog(
                                        title: const Text('确认删除'),
                                        content: const Text('确定要删除这个商品吗？'),
                                        actions: [
                                          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
                                          TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('删除')),
                                        ],
                                      ),
                                    );
                                    if (confirm == true) {
                                      final id = item['id'] is int ? item['id'] as int : int.tryParse((item['id'] ?? '').toString()) ?? 0;
                                      if (id > 0) {
                                        await _deleteGoods(id);
                                      }
                                    }
                                  },
                                  style: OutlinedButton.styleFrom(
                                    foregroundColor: Colors.red,
                                    side: BorderSide(color: Colors.red[300]!),
                                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                                  ),
                                  child: const Text('删除'),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
            ),
    );
  }
}
